/*
 * @Author: 生俊甫 1758142861@qq.com
 * @Date: 2024-06-06 14:03:24
 * @LastEditors: 生俊甫 1758142861@qq.com
 * @LastEditTime: 2024-06-08 14:01:14
 * @FilePath: /sjf/2024-project/2024_centos/pro_knowledge/sql_test.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <string>
#include <mysql/mysql.h>

const std::string host = "localhost";//IP
const std::string user = "xxx";//用户名
const std::string passwd = "xxx";//密码
const std::string db = "xxx";//连接对应数据库
const unsigned int port = 3306;//数据库服务端口号

int main()
{
    //1.创建mysql句柄
    MYSQL* mysql = mysql_init(NULL);
    if(mysql == nullptr)
    {
        std::cout << "mysql init err: " << mysql_error(mysql) << std::endl;
        return -1;
    }
    //2.连接MySQL服务
    if(mysql_real_connect(mysql,host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0) == nullptr)
    {
        std::cout << "mysql connect err: " << mysql_error(mysql) << std::endl;
        return -1;
    }
    //3.设置字符编码集
    if(mysql_set_character_set(mysql,"utf8") != 0)
    {
        std::cout << "mysql set character err: " << mysql_error(mysql) << std::endl;
        return -1;
    }
    //4.执行sql语句
    //新增数据 std::string sql = "insert into stu values(null,'小明',18,89,99,94);";
    //修改用户信息 std::string sql = "update stu set ch=ch-10 where id=2;";
    //删除用户 std::string sql = "delete from stu where id = 2;";
    //查询操作
     
    std::string sql = "select * from stu;";
    int ret = mysql_query(mysql,sql.c_str());
    if(ret != 0)
    {
        std::cout << sql << "--- insert err:" << mysql_error(mysql) << std::endl;
        mysql_close(mysql);
        return -1;
    }
    MYSQL_RES *res = mysql_store_result(mysql);
    if(nullptr == res)
    {
        std::cerr << "mysql_store_result error" << std::endl;
        return 4;
    }
    //获取行和列
    int rows = mysql_num_rows(res);
    int fields = mysql_num_fields(res);
    std::cout << "行:" << rows << std::endl;
    std::cout << "列:" << fields << std::endl;
    //获取属性
    MYSQL_FIELD *fields_array = mysql_fetch_fields(res);
    for(int i = 0; i < fields; i++)
    {
        std::cout << fields_array[i].name << "\t";
    }
    std::cout << "\n";
    //内容
    for(int i = 0; i < rows; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0; j < fields; j++)
        {
            std::cout << row[j] << "\t";//*(row+j);
        }
        std::cout << "\n";
    }
    mysql_free_result(res);
    mysql_close(mysql);
    return 0;
}